package com.project.demo.parser;

import com.google.common.base.Strings;
import com.je.core.service.MetaService;
import com.je.core.service.MetaServiceImpl;
import com.je.core.service.PCDynaServiceTemplate;
import com.je.core.util.JEUUID;
import com.je.core.util.SecurityUserHolder;
import com.je.core.util.SpringContextHolder;
import com.je.core.util.bean.BeanUtils;
import com.je.core.util.bean.DynaBean;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.model.EndUser;
import com.je.rbac.service.RoleManager;
import com.je.thrid.parser.AbstractDynaBeanImportParser;
import com.je.thrid.vo.ParseVo;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

/**
 * @program: je-platform
 * @author: LIULJ
 * @create: 2020/7/26
 * @description：格式化方法，return ParseVo ，vo中包含两个参数，判断是否插入的作用适用于上下级，有些情况是在格式化完成后就要插入，如果为false，就是通一格式化后一起插入
 *                           参数1：deptMent要导入的部门 参数2：customParameters 自定义参数
 */
@Component
public class DepartmentImportParser extends AbstractDynaBeanImportParser {

    @Override
    public ParseVo parse(DynaBean deptMent, JSONObject customParameters) {
        MetaService metaService = SpringContextHolder.getBean(MetaServiceImpl.class);
        deptMent.setStr(BeanUtils.KEY_TABLE_CODE, "JE_CORE_DEPARTMENT");
        // 部门类型
        String rankName = deptMent.getStr("RANKNAME");
        DynaBean deptMentType = metaService.selectOne("JE_CORE_DICTIONARYITEM",
            ConditionsWrapper.builder().eq("DICTIONARYITEM_ITEMNAME", rankName).apply(
                " AND DICTIONARYITEM_DICTIONARY_ID=(select JE_CORE_DICTIONARY_ID from JE_CORE_DICTIONARY WHERE DICTIONARY_DDCODE='JE_GSJB')"),
            "DICTIONARYITEM_ITEMCODE");
        if (deptMentType == null) {
            deptMent.setStr("RANKCODE", "BM");
            deptMent.setStr("RANKNAME", "部门");
        } else {
            deptMent.setStr("RANKCODE", deptMentType.getStr("DICTIONARYITEM_ITEMCODE"));
        }
        String deptNames = deptMent.getStr("DEPTNAME");
        String[] names;
        if (deptNames.indexOf(";") >= 0) {
            String[] szDeptNames = deptNames.split(";");
            for (int i = 1; i < szDeptNames.length; i++) {
                DynaBean newDeptMent = deptMent.setStr("DEPTNAME", szDeptNames[i]);
                parse(newDeptMent, customParameters);
            }
            names = szDeptNames[0].split("/");
        } else {
            names = deptNames.split("/");
        }
        // 上级部门名称
        String parentDeptId = addParentDept(names);
        if (Strings.isNullOrEmpty(parentDeptId)) {
            parentDeptId = "ROOT";
        }
        DynaBean parentDept = metaService.selectOne("JE_CORE_DEPARTMENT",
            ConditionsWrapper.builder().eq("DEPTID", parentDeptId), "DEPTCODE,DEPTNAME,DEPTID,PATH,TREEORDERINDEX");
        if (parentDept == null) {
            parentDept = metaService.selectOne("JE_CORE_DEPARTMENT", ConditionsWrapper.builder().eq("DEPTID", "ROOT"),
                "DEPTCODE,DEPTNAME,DEPTID,PATH,TREEORDERINDEX");
        }
        deptMent.setStr("DEPTNAME", names[names.length - 1]);
        deptMent.setStr("DEPTID", JEUUID.uuid());
        deptMent.setStr("DEPTCODE", JEUUID.uuid());
        deptMent.setStr("PARENTCODE", parentDept.getStr("DEPTCODE"));
        deptMent.setStr("PARENTNAME", parentDept.getStr("DEPTNAME"));
        deptMent.setStr("PARENT", parentDept.getStr("DEPTID"));
        deptMent.setStr("PARENTPATH", parentDept.getStr("PATH"));
        deptMent.setStr("PATH", String.format("%s/%s", parentDept.getStr("PATH"), deptMent.getStr("DEPTID")));
        deptMent.setStr("NODETYPE", "LEAF");
        deptMent = buildDeptInfo(deptMent, parentDept);
        return new ParseVo(deptMent, false);
    }

    private static String addParentDept(String[] names) {
        String[] newNames = new String[names.length - 1];
        for (int i = 0; i < newNames.length; i++) {
            newNames[i] = names[i];
        }
        MetaService metaService = SpringContextHolder.getBean(MetaServiceImpl.class);
        String parentId = "ROOT";
        for (String name : newNames) {
            DynaBean dept = metaService.selectOne("JE_CORE_DEPARTMENT",
                ConditionsWrapper.builder().eq("DEPTNAME", name).like("PARENT", parentId),
                "DEPTCODE,DEPTNAME,DEPTID,PATH,TREEORDERINDEX");
            if (dept == null) {
                if (name.equals("北京科技学院")) {
                    parentId = "ROOT";
                }
                dept = new DynaBean("JE_CORE_DEPARTMENT", true);
                DynaBean parentDept = metaService.selectOne("JE_CORE_DEPARTMENT",
                    ConditionsWrapper.builder().eq("DEPTID", parentId), "DEPTCODE,DEPTNAME,DEPTID,PATH,TREEORDERINDEX");
                parentId = JEUUID.uuid();
                dept.setStr("DEPTNAME", name);
                dept.setStr("DEPTID", parentId);
                dept.setStr("DEPTCODE", parentId);
                dept.setStr("PARENTCODE", parentDept.getStr("DEPTCODE"));
                dept.setStr("PARENTNAME", parentDept.getStr("DEPTNAME"));
                dept.setStr("PARENT", parentDept.getStr("DEPTID"));
                dept.setStr("PARENTPATH", parentDept.getStr("PATH"));
                dept.setStr("PATH", String.format("%s/%s", parentDept.getStr("PATH"), dept.getStr("DEPTID")));
                dept.setStr("NODETYPE", "LEAF");
                dept = buildDeptInfo(dept, parentDept);
            }
            parentId = dept.getStr("DEPTID");
        }
        return parentId;
    }

    private static DynaBean buildDeptInfo(DynaBean deptMent, DynaBean parentDept) {
        MetaService metaService = SpringContextHolder.getBean(MetaServiceImpl.class);
        PCDynaServiceTemplate pcDynaServiceTemplate = SpringContextHolder.getBean(PCDynaServiceTemplate.class);
        RoleManager roleManager = SpringContextHolder.getBean(RoleManager.class);
        pcDynaServiceTemplate.buildModelCreateInfo(deptMent);
        EndUser endUser = SecurityUserHolder.getCurrentUser();
        deptMent.setStr("CREATEORG", endUser.getDeptCode());
        deptMent.setStr("CREATEORGNAME", endUser.getDeptName());
        deptMent.setStr("MODIFYTIME", deptMent.getStr("SY_CREATETIME"));
        deptMent.setStr("CREATETIME", deptMent.getStr("SY_CREATETIME"));
        deptMent.setStr("CREATEUSER", endUser.getUserCode());
        deptMent.setStr("CREATEUSER", endUser.getUsername());
        deptMent.setStr("JTGSMC", endUser.getJtgsMc());
        deptMent.setStr("JTGSDM", endUser.getJtgsDm());
        deptMent.setStr("JTGSID", endUser.getJtgsId());
        deptMent.setStr("GSBMID", endUser.getGsbmId());
        deptMent.setStr("RANKCODE", "BM");
        deptMent.setStr("RANKNAME", "部门");
        deptMent.setStr("ORDERINDEX", deptMent.getStr("DISPLAY_ORDER"));
        deptMent.setStr("ZHID", endUser.getZhId());
        deptMent.setStr("ZHMC", endUser.getZhMc());
        deptMent.setStr("CREATEORG", endUser.getDeptCode());
        deptMent.setStr("CREATEORGNAME", endUser.getDeptName());
        deptMent.setStr("STATUS", "1");
        deptMent.setStr("LAYER", "1");
        deptMent.set("TREEORDERINDEX", parentDept.get("TREEORDERINDEX"));
        roleManager.generateTreeOrderIndex(deptMent);
        metaService.insert(deptMent);
        if (parentDept.getStr("NODETYPE").equals("LEAF")) {
            parentDept.setStr("NODETYPE", "GENERAL");
            metaService.update(parentDept);
        }
        return deptMent;
    }
}
